import updateTreeNodeInfo, {  getFullTreeByXid, getTreeNodeInfoById } from "@/services/basis";
import { CloseOutlined } from "@ant-design/icons";
import { ProCard, ProForm, ProFormDatePicker, ProFormInstance, ProFormRadio, ProFormSelect, ProFormText, useStyle } from "@ant-design/pro-components";
import { useModel, useRequest } from "@umijs/max";
import { Button, Card, Col, DatePicker, Flex, Form, Input, message, Radio, Row, Space, Tree, TreeDataNode } from "antd";
import { times } from "lodash";
import moment from "moment";
import { useRef, useState } from "react";
import { getSelection } from "@/services/selections";

const App:React.FC=()=>{
    const [trNode,setTrNode]=useState<{key:any,title:string}>({key:0,title:''});
    const [trData,setTrData]=useState<TreeDataNode[]>([]);
    const [etype,setEtype]=useState(0);

    const form_ref=useRef<ProFormInstance>();
    const [expandKeys,setExpandKeys]=useState([]);
    const { initialState, setInitialState } = useModel('@@initialState');

    useRequest(()=>getFullTreeByXid({x_id:1,treeType:'workcenter'}),{
        onSuccess:(data)=>{
            setTrData(data.ctree);
            setExpandKeys(data.keys);
        },
    });

    async function getTreeNodeInfo(node:{key:any,title:any}){
       // alert(JSON.stringify(node));
        setEtype(0);
        setTrNode(node);//保存当前的id，在新增时使用
       const info=await getTreeNodeInfoById({treeType:'v_workcenter',key:node.key});
       const fdata={...info.data,
                    operate_time:moment(moment(info.data.operate_time).toDate()).format('YYYY-MM-DD')
             };
      form_ref.current?.setFieldsValue({
                code:fdata.code,name:fdata.name,higher_name:fdata.higher_name,
                operate_time:fdata.operate_time,higher_code:fdata.higher_code,
                status:fdata.status,operater_id:fdata.operater_id,
                type:fdata.type,org_id:fdata.org_id,
                }); 
     }

     //新增
     async function add(){
        if(trNode.key==0)
            message.warning('请先选择所归属的上级工作中心！');
        else{
         setEtype(1);
        //  form_ref.current?.resetFields();
         form_ref.current?.setFieldsValue({
            operate_time:moment(moment().toDate()).format('YYYY-MM-DD'),
            higher_code:trNode.title.substring(0,trNode.title.indexOf(' ')),
            higher_name:trNode.title.substring(trNode.title.indexOf(' '+1)),
            code:'',name:'',org_id:null,operater_id:initialState?.currentUser?.userid,
        });
        };
     };

     //保存
     async function save(){
        const fdata=form_ref.current?.getFieldsValue();
        const fdata2={...fdata,higher_id:trNode?.key, 
                       higher_code:trNode?.title.substring(0,trNode?.title.indexOf(' ')), 
                       id:trNode?.key, 
                       operater_id:initialState?.currentUser?.userid,
                      operate_time:moment(moment(fdata.operate_time).toDate()).format('YYYY-MM-DD HH:mm:ss')};
       //  alert(JSON.stringify(fdata2));
       //mform_ref.current?.submit();
       const r=await updateTreeNodeInfo({x_id:1,operater_id:initialState?.currentUser?.userid,
                  ttype:etype,tdata:fdata2,treeType:'workcenter'});
        if(r.success){
          message.success('数据保存成功！');
          //alert(JSON.stringify(r.data));
          setTrData(r.data);
          }
        else
          message.error('数据保存失败，请检查。');
    
     }
   
     //=======================================================================================
    return(
     <Row gutter={8} >
         <Col span={6}>
         <ProCard title='工作中心' style={{height:'75vh',overflow:'auto'}}>
            <Tree treeData={trData}   blockNode={true}
               expandedKeys={expandKeys}
               onExpand={(keys:any)=>setExpandKeys(keys)}
               onClick={(e,node)=>getTreeNodeInfo({key:node.key,title:node.title?.toString()})}
            />
         </ProCard>
         </Col>
         <Col span={18}>
         <ProCard title='基本信息' style={{height:'75vh',overflow:'auto'}} 
              extra={<Space>
                <Button onClick={()=>add()}>新增工作中心</Button>
                <Button onClick={()=>form_ref.current?.submit()}>保存工作中心</Button></Space>}>
                {/* {JSON.stringify(trNode)} */}
            <ProForm labelCol={{offset:0, span:8}} formRef={form_ref} style={{width:500,marginLeft:100}}
               initialValues={{status:1,operate_time:moment(moment().toDate()).format('YYYY-MM-DD'),
                        operater_id:initialState?.currentUser?.userid}}
               submitter={{
                 submitButtonProps:{style:{display:'none'}},
                 resetButtonProps:{style:{display:'none'}}
               }}  layout="horizontal" labelAlign="left" 
               onFinish={()=>save()}
              >
                <ProFormText name='code' label='工作中心编码' rules={[{required:true,message:'编码必须输入！'}]}/>
                <ProFormText name='name' label='工作中心名称' rules={[{required:true,message:'名称必须输入！'}]}/>
                <ProFormText name='higher_code' label='上级编码' disabled/>
                <ProFormText name='higher_name' label='上级名称' disabled/>
                <ProFormRadio.Group name='type' label='类别' 
                    options={[{value:1,label:'生产车间'},{value:2,label:'辅助车间'},{value:3,label:'其他车间'}]} />
                <ProFormRadio.Group name='status' label='状态'
                    options={[{label:'正常',value:1},{label:'关闭',value:2,style:{color:'blue'}},{label:'删除',value:3,style:{color:'red'}}]}
                    />
                <ProFormSelect name='org_id' label='所属部门' 
                       fieldProps={{
                                    showSearch:true,
                                     }}
                       request={async ()=>{
                                           var x:any=await getSelection({source: 'base_organization', x_id: 1 });
                                           var x2=x.data.map((item:any)=>({value:item.id,label:item.name}));
                                            return x2;
                                    }}
                  />
                
                   <ProFormDatePicker name='operate_time' label='修改时间' />
                   <ProFormSelect name='operater_id' label='修改人' 
                       fieldProps={{
                                    showSearch:true,
                                     }}
                       request={async ()=>{
                                           var x:any=await getSelection({source: 'base_person', x_id: 1 });
                                           var x2=x.data.map((item:any)=>({value:item.id,label:item.name}));
                                            return x2;
                                    }}
                  />
                
             </ProForm>
         </ProCard>
         </Col>
     </Row>
);
}

export default App;